<?php
defined('IN_MAIN') or exit('Invalid Access!');
    
function format_ad($page){
 global $vars;
 $db=$vars["db"];
 $block=200;
 $page_d=$page;

 preg_match_all('/\<%ad_tid:\d+\#\d+%\>/', $page, $match);
 for($i=0;$i<count($match[0]);$i++){
  unset($match2);
  preg_match('/(?<=tid:)\d+/', $match[0][$i], $match2);
  $r_ad_type[$match2[0]]++;//array[ad type id]=ad count
  $r_ad_type_no[$match2[0]][]=$match[0][$i];//array[ad type id][]=ad type numbering
 }//print_r($r_ad_type);print_r($r_ad_type_no);


 $count=@mysql_result(mysql_query("select count(*) from $db->banner_ad where status='active'"), 0) or 0;
 $bl=5;
 $bl_no=ceil($count/$bl);
 $limit_start=rand(0, $bl_no-1)*$bl;
 mysql_query("select * from $db->banner_ad where status='active' limit $limit_start, $bl");
 mysql_query("select * from $db->banner_ad where status='active' limit 5 order by rand()");

 if(count($r_ad_type)){
  $r=mysql_query("select * from $db->ad_type");
  for($i=0,$t=@mysql_num_rows($r);$i<$t;$i++){
   $adt=mysql_fetch_assoc($r);
   $ad_type[$adt["id"]]=$adt;
  }
  foreach($r_ad_type as $tid=>$ad_count){
   //randomize banner ad
   unset($r_ad_bn);
   $count=@mysql_result(mysql_query("select count(*) from $db->banner_ad where status='active' and tid='$tid'"), 0) or 0;
   $block_no=ceil($count/$block);
   $limit_start=rand(0, $block_no-1)*$block;
   $r2=mysql_query("select * from $db->banner_ad where status='active' and tid='$tid' limit $limit_start, $block");
   for($i=0,$t=@mysql_num_rows($r2);$i<$t;$i++){
    $r_ad_bn[$i]=mysql_fetch_assoc($r2);
   }
   if(count($r_ad_bn)){
    shuffle($r_ad_bn);
   }

   unset($r_ad_display);
   for($i=0;$i<$ad_count;$i++){
    if(count($r_ad_bn)){
     $ad_bn=array_pop($r_ad_bn);
     $id=$ad_bn["id"];
     $all_bn_id.="$id,";
     $type=$ad_bn["type"];
     $value=$ad_bn["display_value"];
     $width=$ad_type[$ad_bn["tid"]]["width"];
     $height=$ad_type[$ad_bn["tid"]]["height"];
     if($type=="i"){//image
      if(preg_match('/\.swf$/', $value)){
       $ad_display=(USER_BROWSER=="firefox"? "<span class='flash_ff'>" : "")."<div class='flash_ad fl$width"."x$height'><a href='view_ad.php?id=$id' target='_blank'><img src='images/spacer.gif' /></a>".format_flash(AD_URL. "/$ad_bn[ad_key]/$value", $width, $height)."</div>".(USER_BROWSER=="firefox"? "</span>" : "");
      }else{
       $ad_display="<a href=\"view_ad.php?id=$id\" target='_blank'><img src='".AD_URL. "/$ad_bn[ad_key]/$value' width='$width' height='$height' /></a>";
      }
     }else{//type=s - script
      $ad_display="<div style='width:$width"."px; height:$height"."px; overflow:hidden;'>$value</div>";
     }
    }
    $r_ad_display[$i]=$ad_display;
   }//for each ad count

   //replace to page
   for($i=0;$i<$ad_count;$i++){
    $page_d=str_replace($r_ad_type_no[$tid][$i], $r_ad_display[$i], $page_d);
   }
  }//for each ad type

  //update ad statistics
  $all_bn_id=rtrim($all_bn_id, ",");
  if($all_bn_id){
   $r_all_id=explode(",", $all_bn_id);
   for($i=0;$i<count($r_all_id);$i++){
    check_deduct_banner_ad_day($r_all_id[$i]);
    add_banner_ad_view($r_all_id[$i]);
   }
  }
 }

 return $page_d;
}

function check_deduct_banner_ad_day($id){
 global $vars;
 $db=$vars["db"];
 $r=mysql_query("select * from $db->banner_ad where id='$id'");
 if(@mysql_num_rows($r)){
  $ad=mysql_fetch_assoc($r);
  if(ntime()>strtotime($ad["next_check"])){
   if($ad["day"]>0){
    $new_checkpoint=date("Y-m-d", timed()+86400)." ".substr($ad["next_check"], -8);
    if(!mysql_query($sql="update $db->banner_ad set day=day-1, next_check='$new_checkpoint' where id='$id'")){
     $a_sqlerr.="$sql<br />\n".mysql_error()."<br />\n";
    }
   }elseif($ad["day"]!=-100){//ad is not unlimited, and remaining day=0
    if(!mysql_query($sql2="update $db->banner_ad set status='expired', remain_time='0' where id='$id'")){
     $a_sqlerr.="$sql2<br />\n".mysql_error()."<br />\n";
    }elseif(!mysql_query($sql3="insert into $db->banner_ad_history (uid, aid, originator, type, cdate) values ('$ad[uid]', $id, 's', 'expire', '".ndate("Y-m-d H:i:s")."')")){
     $a_sqlerr.="$sql3<br />\n".mysql_error()."<br />\n";
    }
    //email user
    $r_user=@mysql_fetch_assoc(mysql_query("select * from $db->users where id='$ad[uid]'"));
    $u_sub=replace_tag(__("<%title%> - Your Banner Ad had expired"), array("<%title%>"=>$vars["title"]));
    $u_msg=replace_tag(__("Dear <%name%>,\n\nYour banner ad '<%title%> had just expired. You can check your banner ad <a href='<%url%>'>here</a>."), array("\n"=>"<br />\n", "<%name%>"=>$r_user["username"], "<%title%>"=>$ad["title"], "<%url%>"=>M_URL. "/ad.php?type=edit&id=$ad[ad_key]"));
    email_user($r_user["email"], $u_sub, $u_msg);
   }
   if($a_sqlerr){
    $a_sub="$vars[title] - System Update Banner Ad Failed";
    $a_msg=
    "<p>Dear admin,</p>
    <p>Error occured while executing function check_deduct_banner_ad_day().<br />\n<br />\nSQL error: $a_sqlerr</p>";
    email_admin($a_sub, $a_msg);
   }
  }
 }
 return !$error;
}
?>